<template>
  <div>
    <el-card>
      <div id="containerNavigation"></div>
      <el-card id="pointInfo">
        <el-form>
          <el-form-item>
            起点:<el-input v-model="start" placeholder="起点"></el-input>
          </el-form-item>
          <el-form-item>
            终点<el-input v-model="end" placeholder="终点"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getPathPlan">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-card>

    <!-- 显示路径规划信息 -->
    <el-card id="pathInfo">
      <el-steps direction="vertical" :active="1">
        <el-step
          v-for="(i, index) in pathPlanRes"
          :title="i.instruction"
        ></el-step>
      </el-steps>
      <!-- <div id="panel"></div> -->
    </el-card>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { shallowRef } from "@vue/reactivity";
import { ref, reactive, nextTick } from "vue";
import axios from "axios";
import { pathPlan } from "@/networks/pathPlan.js";
import { ElMessage } from "element-plus";
export default {
  name: "navigation",
  setup(context, props) {
     window._AMapSecurityConfig = {
      securityJsCode: "7a147469fc71afc2c2540196e2453b2b",
    };
    const map = shallowRef(null);
    const start = ref("");//起点
    const end = ref("");//终点
    const startLnglat = reactive({ lng: null, lat: null }); //起点经纬度
    const endLnglat = reactive({ lng: null, lat: null }); //终点经纬度
    const pathPlanRes = reactive([]);//存储路线数组
    const flag = ref(0);
    // 经纬度坐标转换函数
    async function getLnglat(start, end) {
      try {
        const { data: startPoint } = await axios.get(
          `https://restapi.amap.com/v3/geocode/geo?key=f58766337111f56d9101db384fbea982&address=${start}`
        );
        const { data: endPoint } = await axios.get(
          `https://restapi.amap.com/v3/geocode/geo?key=f58766337111f56d9101db384fbea982&address=${end}`
        );
        // console.log(startPoint,endPoint)
        let a = startPoint.geocodes[0].location.split(",");
        let b = endPoint.geocodes[0].location.split(",");
        startLnglat.lng = a[0];
        startLnglat.lat = a[1];
        endLnglat.lng = b[0];
        endLnglat.lat = b[1];
      } catch (err) {
        console.log(err);
      }
      // console.log(startLnglat,endLnglat)
    }
    //经纬度坐标转换
    return {
      getLnglat,
      map,
      start,
      end,
      startLnglat,
      endLnglat,
      pathPlanRes,
      flag,
    };
  },
  methods: {
    initMap() {
      let instance = this;
      AMapLoader.load({
        key: "2b45c6a7655404e69a9b856504d8625c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      })
        .then((AMap) => {
          this.map = new AMap.Map("containerNavigation", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [117.301291, 31.844148], //初始化地图中心点位置
            // mapStyle: 'amap://styles/darkblue'
          });
          //   导入地图插件
          AMap.plugin("AMap.Driving", function () {
            var driving = new AMap.Driving({
              // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
              policy: AMap.DrivingPolicy.LEAST_TIME,
              // map 指定将路线规划方案绘制到对应的AMap.Map对象上
              map: instance.map,
              // panel: 'panel'
              // panel 指定将结构化的路线详情数据显示的对应的DOM上，传入值需是DOM的ID
            });

            // 搜索完成后，将自动绘制路线到地图上
            if(instance.flag && instance.startLnglat.lng != null && instance.startLnglat.lat != null)//首次加载地图不进行路线规划加载
            {
              driving.search([instance.startLnglat.lng,instance.startLnglat.lat],[instance.endLnglat.lng,instance.endLnglat.lat]);
            }
            else{
              instance.flag++;//第二次加载地图时标志变为1
            }
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },

    // 获取规划路径
    async getPathPlan() {
      await this.getLnglat(this.start, this.end);
      const { data: res } = await pathPlan({
        key: "f58766337111f56d9101db384fbea982",
        origin: `${this.startLnglat.lng},${this.startLnglat.lat}`,
        destination: `${this.endLnglat.lng},${this.endLnglat.lat}`,
      });

      if (res.status != "1") {
        // console.log(res);
        return ElMessage.error("获取路径失败");
      } else {
        // console.log(res.route.paths.length);
        // 首先将数据进行格式化为一个对象数组方便数据显示
        for (let i = 0; i < res.route.paths.length; i++) {
          // console.log(res.route.paths[i]);
          for (let j = 0; j < res.route.paths[i].steps.length; j++) {
            this.pathPlanRes.push(res.route.paths[i].steps[j]);
          }
        }
        this.map.destroy();
        nextTick(()=>{
          this.initMap();//重绘地图
        })
        // console.log(this.pathPlanRes);
        return ElMessage.success("获取成功");
      }
    },
  },
  activated() {
    // 页面活动时加载地图容器
    this.initMap();
  },
  deactivated() {
    //页面失去焦点后删除地图容器
    this.map.destroy();
  },
};
</script>

<style lang="less" scoped>
#containerNavigation {
  width: calc(100vw - 200px);
  height: calc(100vh - 3rem);
  position: absolute;
  top: 3rem;
  left: 200px;
  z-index: 1;
}
#pointInfo {
  position: absolute;
  z-index: 10;
}

#pathInfo {
  position: absolute;
  z-index: 10;
  right: 0;
  top: 3rem;
  overflow: auto;
  height: calc(100vh - 4rem);
  padding: 0;
  margin-top: 0.5rem;
  max-width: 30vw;
}

.el-form {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.el-steps {
  // width: 10rem;
  height: calc(100vh - 5rem);
  overflow: auto;
}
</style>
